﻿using System;
using System.Transactions;
using Common;
using Dto;
using SqlServerDAL;

namespace Business
{
    public class SportsGroupBusiness
    {
        private const string Waming = "Business.SportsTeamBusiness";
        private readonly SportsGroupDAL sportsGroupDal = new SportsGroupDAL();

        /// <summary>
        /// 保存小组信息
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="annexDto"></param>
        /// <returns></returns>
        public bool SaveGroup(SportsGroupDto dto, AnnexDto annexDto)
        {
            var tran = new TransactionScope();
            try
            {
                var annexBusiness = new AnnexBusiness();
                var logoId = 0;
                if (annexDto != null)
                {
                    annexDto = annexBusiness.AddAnnex(annexDto);
                    logoId = annexDto.AnnexID;
                }
                dto.GroupLogo = logoId;
                sportsGroupDal.Save(dto);
                tran.Complete();
                return true;
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError(Waming + ".SaveTeam(SportsTeamDto dto)", ex);
                return false;
            }
            finally
            {
                tran.Dispose();
            }
        }

        public bool ApplyToJoin(int userId, int teamId)
        {
            return false;
        }

        public SportsGroupDto GetGroupById(int id)
        {
            try
            {
                SportsGroupDto dto = null;
                var entity = sportsGroupDal.FindById(id);
                if (entity != null)
                {
                    dto = FillDto.FillSportsGroupDto(entity);
                }
                return dto;
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError(Waming + ".GetGroupById(int id)", ex);
                return null;
            }
        }

        public SportsGroupDto GetGroupByCode(string code)
        {
            try
            {
                SportsGroupDto dto = null;
                var entity = sportsGroupDal.FindOne(code);
                if (entity != null)
                {
                    dto = FillDto.FillSportsGroupDto(entity);
                }
                return dto;
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError(Waming + ".GetGroupById(int id)", ex);
                return null;
            }
        }
    }
}